﻿open System.Windows.Forms
// open System.Linq

open Mono.Cecil

open CodeBlock

let form = new Form()

let types = new TreeView(Dock = DockStyle.Fill)
let fields = new ListBox(Dock = DockStyle.Bottom)

form.Controls.Add(fields)
form.Controls.Add(types)
types.BringToFront()

let resolver = DefaultAssemblyResolver()
let assembly = resolver.Resolve(typeof<int>.Assembly.FullName)
for mdef in assembly.Modules do
    let mnode = types.Nodes.Add(mdef.Name)
    mnode.Tag <- mdef
    
    let namespaceNode (ns: string) =
        let parts = ns.Split([|'.'|]) |> List.of_array
        
        let rec node (current: TreeNode) names =
            match names with
            | [] -> current
            | name :: rest ->
                let child =
                    match current.Nodes |> Seq.cast<TreeNode> |> Seq.tryFind(fun node -> node.Text = name) with
                    | None ->
                        current.Nodes.Add(name)
                    | Some(child) ->
                        child
                
                node child rest
        
        node mnode parts
    
    for tdef in mdef.Types do
        let tnode = namespaceNode tdef.FullName
        tnode.Tag <- tdef

let highLevel = HighLevel()

types.AfterSelect.Add(
    fun _ ->
        if types.SelectedNode <> null then
            match types.SelectedNode.Tag with
            | :? TypeReference as tref ->
                let tdef = highLevel.Morf tref
                fields.Items.Clear()
                for field in tdef.Fields do
                    fields.Items.Add(sprintf "%s: %s" field.Name field.FieldType.FullName)
            | _ ->
                fields.Items.Clear()
)

form.Text <- assembly.Name.ToString()

Application.Run(form)
